import axios from 'axios'
import { Toast } from 'vant';
import $route from '../router/index'

var service = axios.create({
    timeout: 10 * 1000,
    baseURL: '/api'
})

// 设置请求拦截
service.interceptors.request.use((config) => {
    // 设置请求头
    config.headers['Authorization'] = 'Bearer' + ' ' + localStorage.getItem('token');
    // 显示加载中
    Toast.loading({
        message: '加载中...',
    });
    return config;
}, (error) => {
    return Promise.reject(error)
})
// 设置响应拦截
service.interceptors.response.use((res) => {
    Toast.clear(); //隐藏loading
    return res;
}, (error) => {
    Toast.clear(); //隐藏loading
    if (error.response.status == 401) {
        Toast.fail('身份认证过期，请重新登录');
        // 登录过期，重新登录
        localStorage.removeItem('token')
        $route.push('/login');
    } else if (error.response.status == 400) {
        Toast.fail('请求错误');
    } else if (error.response.status == 404) {
        Toast.fail('访问路径有误');
    } else if (error.response.status == 500) {
        Toast.fail('失败文案');
    }
})

export default service